package com.drinks.yiniang.ui.activity.camera;

import android.content.Intent;
import android.nfc.Tag;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.photo.PreviewPhotosAdapter;
import com.drinks.yiniang.common.camera.CropViewContainerHelper;
import com.drinks.yiniang.common.camera.album.Result;
import com.drinks.yiniang.common.camera.album.entity.GoodsTagPoints;
import com.drinks.yiniang.common.camera.album.entity.TagPoints;
import com.drinks.yiniang.entity.common.UploadImageJson;
import com.drinks.yiniang.entity.photo.Photos;
import com.drinks.yiniang.ui.activity.community.CommunityPublishActivity;
import com.drinks.yiniang.ui.activity.search.SearchGoodsTagActivity;
import com.drinks.yiniang.ui.widget.image.CropFixImageView;
import com.drinks.yiniang.ui.widget.layout.RandomDragTagLayout;
import com.drinks.yiniang.ui.widget.view.RandomDragTagView;
import com.hansen.library.Constants;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.ui.widget.recycler.PreviewRecyclerView;
import com.hansen.library.utils.ColorUtils;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.ScreenSizeUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 预览图片
 *
 * @author han
 * @date 2019/09/16
 */
public class PreviewPhotosActivity extends BaseTranBarActivity implements OnNavgationBarClickListener, RandomDragTagLayout.OnClickPointsAddTagListener {

    private final int REQ_SELECT_GOODS_CODE = 0x01;

    //nav
    private NavigationBarLayout nav_bar_preview_photos;
    private PreviewRecyclerView rcv_preview_photos;
    private FrameLayout fl_preview_photos_crop_view;
    //tips
    private TextView tv_preview_photos_tag_tips;

    private PreviewPhotosAdapter mPreviewPhotosAdapter;
    private PagerSnapHelper mSnapHelper;
    private LinearLayoutManager mLayoutManager;

    //剪裁view或videoView填充辅助类
    private CropViewContainerHelper cropViewContainerHelper;

    //x,y
    private float mTagX, mTagY;

    @Override
    protected void initView() {
        nav_bar_preview_photos = findViewById(R.id.nav_bar_preview_photos);

        rcv_preview_photos = findViewById(R.id.rcv_preview_photos);

        fl_preview_photos_crop_view = findViewById(R.id.fl_preview_photos_crop_view);

        tv_preview_photos_tag_tips = findViewById(R.id.tv_preview_photos_tag_tips);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        //剪裁控件辅助类
        cropViewContainerHelper = new CropViewContainerHelper(fl_preview_photos_crop_view);

        initAdapter();
        setTipsText();
        setNavTitleFormat(1, mPreviewPhotosAdapter.getData().size());
    }

    private void initAdapter() {
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rcv_preview_photos.setLayoutManager(mLayoutManager);
        //rcv_preview_photos.scrollToPosition(position);

        mPreviewPhotosAdapter = new PreviewPhotosAdapter(mContext, new ArrayList<Photos>());
        mPreviewPhotosAdapter.bindToRecyclerView(rcv_preview_photos);
        mSnapHelper = new PagerSnapHelper();
        mSnapHelper.attachToRecyclerView(rcv_preview_photos);

        CropFixImageView mCropView;

        for(Photos data : Result.mPhotos) {
            mCropView = cropViewContainerHelper.loadCropView(mContext, data);
            cropViewContainerHelper.addCropView(mCropView, data);
        }

        mPreviewPhotosAdapter.addData(Result.mPhotos);
    }

    @Override
    protected void initListener() {
        nav_bar_preview_photos.setOnNavgationBarClickListener(this);
        tv_preview_photos_tag_tips.setOnClickListener(this);
        mPreviewPhotosAdapter.setOnAddTagClickLiesener(this);
        addRecyclerScrollListener();
    }

    private void addRecyclerScrollListener() {
        rcv_preview_photos.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                View view = mSnapHelper.findSnapView(mLayoutManager);
                if (view == null) {
                    return;
                }
                int position = mLayoutManager.getPosition(view);

                setNavTitleFormat(position + 1, mPreviewPhotosAdapter.getData().size());
            }
        });
    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_preview_photos;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {
        //下一步
        doNextStep();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Constants.RESULT_CODE_NORMAL && requestCode == REQ_SELECT_GOODS_CODE) {
            if(data != null) {
                View view = mSnapHelper.findSnapView(mLayoutManager);
                if (view == null) {
                    return;
                }
                int position = mLayoutManager.getPosition(view);

                Photos itemData = mPreviewPhotosAdapter.getItem(position);

                if(mPreviewPhotosAdapter.getTagList() == null || itemData == null) {
                    return;
                }

                if(mPreviewPhotosAdapter.getTagList().get(itemData) == null) {
                    mPreviewPhotosAdapter.getTagList().put(itemData, new ArrayList<GoodsTagPoints>());
                }

                GoodsTagPoints points = new GoodsTagPoints(itemData, data.getStringExtra(Constants.KeyGoodsId), data.getStringExtra(Constants.KeyName), data.getStringExtra(Constants.KeyMoney), mTagX, mTagY, false);

                mPreviewPhotosAdapter.getTagList().get(itemData).add(points);

                mPreviewPhotosAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onTagAddClick(Photos photos, float x, float y) {
        mTagX = x;
        mTagY = y;

        startActivityForResult(new Intent(mContext, SearchGoodsTagActivity.class), REQ_SELECT_GOODS_CODE);
    }

    @Override
    public void onTagDragChange(RandomDragTagView tagView, Photos photos, float x, float y, boolean isLeft) {
        if(mPreviewPhotosAdapter.getTagList() == null || photos == null || mPreviewPhotosAdapter.getTagList().get(photos) == null) {
            return;
        }

        List<GoodsTagPoints> tagPointList = mPreviewPhotosAdapter.getTagList().get(photos);

        for(GoodsTagPoints points : tagPointList) {
            if(tagView == points.getTagView()) {
                points.setX(x);
                points.setY(y);
                points.setShowLeft(isLeft);
                break;
            }
        }
    }

    private void doNextStep() {
        showLoadingDialog();

        List<UploadImageJson.UploadImageData> imgsList = new ArrayList<>();
        List<TagPoints> pointList;

        for(Photos itemData : mPreviewPhotosAdapter.getData()) {
            pointList = new ArrayList<>();

            itemData = cropViewContainerHelper.generateCropUrl(itemData);

            UploadImageJson.UploadImageData data = new UploadImageJson.UploadImageData();

            if(mPreviewPhotosAdapter.getTagList().get(itemData) != null) {
                for(GoodsTagPoints points : mPreviewPhotosAdapter.getTagList().get(itemData)) {
                    pointList.add(new TagPoints(points.getGoodsId(), points.getGoodsName(), points.getGoodsPrice(), points.getX(), points.getY(), points.isShowLeft()));
                }
            }

            data.setAbsolutePath(itemData.cropPath);
            data.setWdith(itemData.width);
            data.setHeight(itemData.height);
            data.setName(itemData.name);
            data.setTagPoints(pointList);

            imgsList.add(data);
        }

        dismissDialog();

        Intent intent = new Intent(mContext, CommunityPublishActivity.class);
        intent.putExtra(Constants.KeyList, (Serializable) imgsList);

        startActivity(intent);

        setResult(Constants.RESULT_CODE_NORMAL);
        finish();
    }

    private void setNavTitleFormat(int current, int total) {
        nav_bar_preview_photos.setNavBarTitle(String.format(getString(R.string.text_edit_photos_format),current, total));
    }

    private void setTipsText() {
        SpannableStringBuilder builder = new SpannableStringBuilder(getString(R.string.text_click_photo_to_add_goods_info));
        builder.append("\n");
        int start = builder.length();
        builder.append(getString(R.string.text_best_content_will_be_seen_by_more_people));
        builder.setSpan(new ForegroundColorSpan(ColorUtils.getColorById(mContext, R.color.alphawhite70)), start, builder.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        builder.setSpan(new AbsoluteSizeSpan(ScreenSizeUtils.sp2Px(mContext, 12)), start, builder.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        tv_preview_photos_tag_tips.setText(builder);
    }
}
